﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Imaging;

namespace WLWeb.RandomPage
{
    public partial class CreateImg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateCheckCodeImage(GenerateCheckCode()); 
        }
        /// <summary>

    /// 生成随机校验码字符串

    /// </summary>

    /// <returns>生成的随机校验码字符串 </returns>

    public string GenerateCheckCode()
    {

        int number;

        string strCode = string.Empty;

        //随机数种子

        Random radom = new Random();

        for (int i = 0; i < 4; i++)
        {

            //随机的整数

            number = radom.Next();

            //字符从０－９，Ａ－Ｚ中随机产生，对应的ＡＳＣＩＩ码分别为48-57,65,90

            number = number % 36;

            if (number < 10)
            {

                number += 48;

            }

            else
            {

                number += 55;

            }

            strCode += ((char)number).ToString();

        }

        //在Cookie中保存校验码或Session中

        //Response.Cookies.Add(new HttpCookie("CheckCode", strCode));
        Session["CheckCode"] = strCode;
        return strCode;

    }

    /// <summary>

    /// 根据校验码输出图片

    /// </summary>

    /// <param name="checkCode">产生的随机校验码 </param>

    public void CreateCheckCodeImage(string checkCode)
    {

        //若校验码为空，则直接返回

        if (checkCode == null || checkCode.Trim() == string.Empty)
        {

            return;

        }

        //根据校验码的长度确定输出图片的长度

        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(decimal.Parse((checkCode.Length * 15) + "")), 20);

        //创建ＧＲＡＰＨＩＣＳ对象

        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

        try
        {

            //生成随机数种子

            Random random = new Random();

            //清空图片背景色

            g.Clear(System.Drawing.Color.White);

            //画图片的背景噪音线１０条

            for (int i = 0; i < 10; i++)
            {

                //噪音线起点坐标（x1,y1），终点坐标（x2,y2）

                int x1 = random.Next(image.Width);

                int x2 = random.Next(image.Width);

                int y1 = random.Next(image.Height);

                int y2 = random.Next(image.Height);

                //用银色画出噪音线

                g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);

            }

            //输出图片中校验码的字体：１２号Arial,粗斜体

            System.Drawing.Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));

            //线形渐变画刷

            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.Purple, 1.2f, true);

            g.DrawString(checkCode, font, brush, 2, 3);

            //画图片的前景噪音点５０个

            for (int i = 0; i < 50; i++)
            {

                int x = random.Next(image.Width);

                int y = random.Next(image.Height);

                image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));

            }

            //画图片的边框线

            g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.SaddleBrown), 0, 0, image.Width - 1, image.Height - 1);

            //创建内存流用于输出图片

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                //图片格式指定为ＰＮＧ

                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                //清除缓冲区流中的所有输出

                Response.ClearContent();

                //输出流的ＨＴＴＰＭＩＭＥ类型设置为＂image/Png＂

                Response.ContentType = "image/Png";

                //输出图片的二进制流

                Response.BinaryWrite(ms.ToArray());

            }

        }

        finally
        {

            //释放 Ｂitmap 对象和 Ｇraphics 对象

            g.Dispose();

            image.Dispose();

        }
    }

    }
}